﻿using System;
using System.Text;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MxWeiXinPF.Common;
using MxWeiXinPF.Web.UI;

namespace MxWeiXinPF.Web.admin.users
{
    public partial class user_list : ManagePage
    {
        protected MxWeiXinPF.Model.manager admin_info;
        protected int group_id;
        protected string keywords = string.Empty;
        protected int page;
        protected int pageSize;
        protected int totalCount;
        protected int wid = 0;
        private BLL.wx_shop_coupon bcoupon = new BLL.wx_shop_coupon();
        private Model.wx_shop_coupon mcoupon = null;

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                base.ChkAdminLevel("user_list", MXEnums.ActionEnum.Delete.ToString());
                int num = 0;
                int num2 = 0;
                MxWeiXinPF.BLL.users users = new MxWeiXinPF.BLL.users();
                for (int i = 0; i < this.rptList.Items.Count; i++)
                {
                    int id = Convert.ToInt32(((HiddenField)this.rptList.Items[i].FindControl("hidId")).Value);
                    CheckBox box = (CheckBox)this.rptList.Items[i].FindControl("chkId");
                    if (box.Checked)
                    {
                        if (users.Delete(id))
                        {
                            num++;
                        }
                        else
                        {
                            num2++;
                        }
                    }
                }
                base.AddAdminLog(MXEnums.ActionEnum.Delete.ToString(), string.Concat(new object[] { "删除用户", num, "条，失败", num2, "条" }));
                base.JscriptMsg(string.Concat(new object[] { "删除成功", num, "条，失败", num2, "条！" }), CombUrlTxt("user_list.aspx", "group_id={0}&keywords={1}", new string[] { this.group_id.ToString(), this.keywords }), "Success");
            }
            catch
            {
            }
        }

        protected void btn_batchSendTick_Click(object sender, EventArgs e)
        {
            try
            {
                base.ChkAdminLevel("user_list", MXEnums.ActionEnum.Delete.ToString());
                int num = 0;
                int num2 = 0;
                MxWeiXinPF.BLL.users users = new MxWeiXinPF.BLL.users();
                for (int i = 0; i < this.rptList.Items.Count; i++)
                {
                    int id = Convert.ToInt32(((HiddenField)this.rptList.Items[i].FindControl("hidId")).Value);
                    CheckBox box = (CheckBox)this.rptList.Items[i].FindControl("chkId");
                    if (box.Checked)
                    {

                        if (SendTicket(id.ToString()))
                        {
                            num++;
                        }
                        else
                        {
                            num2++;
                        }
                    }
                }
                base.AddAdminLog(MXEnums.ActionEnum.Delete.ToString(), string.Concat(new object[] { "送券", num, "条，失败", num2, "条" }));
                base.JscriptMsg(string.Concat(new object[] { "送券成功", num, "条，失败", num2, "条！" }), CombUrlTxt("user_list.aspx", "group_id={0}&keywords={1}", new string[] { this.group_id.ToString(), this.keywords }), "Success");
            }
            catch
            {
            }
        }
        private bool SendTicket(string userid)
        {
            BLL.users buser = new BLL.users();
            string couponid = this.ddlCouponId.SelectedValue;
            BLL.wx_shop_coupon bcoupon = new BLL.wx_shop_coupon();
            Model.wx_shop_coupon mcoupon = bcoupon.GetModel(int.Parse(couponid));
            Model.users muser = buser.GetModel(Convert.ToInt32(userid));
            BLL.wx_shop_coupon_data bcoupondata = new BLL.wx_shop_coupon_data();
            if (muser != null && mcoupon != null)
            {
                DataSet ds = bcoupondata.GetList(string.Format("senduid = {0} and couponid={1} ", userid, mcoupon.id));
                if (ds == null || ds.Tables[0].Rows.Count == 0)
                {
                    List<Model.wx_shop_coupon_data> datas = bcoupondata.DataTableToList(ds.Tables[0]);
                    if (datas.Count >= mcoupon.numperuser)
                    {
                        return false;
                    }
                    else
                    {
                        Model.wx_shop_coupon_data thecoupon = new Model.wx_shop_coupon_data();
                        thecoupon.couponid = mcoupon.id;
                        thecoupon.shopid = base.GetAdminInfo().id;
                        thecoupon.openid = muser.wxOpenId;
                        thecoupon.gettype = 0;
                        thecoupon.status = 0;
                        thecoupon.gettime = DateTime.Now;
                        thecoupon.usetime = DateTime.Now;
                        thecoupon.senduid = muser.id;
                        thecoupon.ordersn = 0;
                        thecoupon.sendmsgstate = 0;
                        thecoupon.sendmsgtime = DateTime.Now;

                        if (bcoupondata.Add(thecoupon) > 0)
                        {

                            //送券成功,增加日志记录
                            Model.wx_shop_coupon_log log = new Model.wx_shop_coupon_log();
                            log.shopid = base.GetAdminInfo().id;
                            log.openid = muser.wxOpenId;
                            log.times = DateTime.Now;
                            log.couponid = mcoupon.id;
                            log.orderid = 0;
                            log.explain = "后台赠送用户";
                            log.remark = " ";
                            log.exstr1 = " ";
                            new BLL.wx_shop_coupon_log().Add(log);
                            return true;
                        }

                    }
                }
            }
            return false;
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            base.Response.Redirect(CombUrlTxt("user_list.aspx", "group_id={0}&keywords={1}", new string[] { this.group_id.ToString(), this.txtKeywords.Text }));
        }

        protected void btnSmsPost_Click(object sender, EventArgs e)
        {
            MxWeiXinPF.BLL.users users = new MxWeiXinPF.BLL.users();
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < this.rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)this.rptList.Items[i].FindControl("hidId")).Value);
                CheckBox box = (CheckBox)this.rptList.Items[i].FindControl("chkId");
                if (box.Checked)
                {
                    MxWeiXinPF.Model.users model = users.GetModel(id);
                    if (!((model == null) || string.IsNullOrEmpty(model.mobile)))
                    {
                        builder.Append(model.mobile + ",");
                    }
                }
            }
            if (!string.IsNullOrEmpty(builder.ToString()))
            {
                base.Response.Redirect("user_sms.aspx?mobiles=" + Utils.UrlEncode(Utils.DelLastComma(builder.ToString())));
            }
        }

        protected string CombSqlTxt(int _wid, int _group_id, string _keywords)
        {
            StringBuilder builder = new StringBuilder();

            //if (_wid != 0)
            //{
            //    builder.Append(" and a.wid=" + _wid);
            //}
            if (_group_id > 0)
            {
                builder.Append(" and a.group_id=" + _group_id);
            }
            _keywords = _keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(_keywords))
            {
                builder.Append(" and (a.user_name like '%" + _keywords + "%' or a.mobile like '%" + _keywords + "%' or a.email like '%" + _keywords + "%' or a.nick_name like '%" + _keywords + "%')");
            }
            if (this.admin_info != null)
            {
                if (this.admin_info.id != 0x27)
                {
                    builder.Append(" and a.shopid=" + this.admin_info.id);
                }
            }
            else
            {
                this.admin_info = base.GetAdminInfo();
                if (this.admin_info.id != 0x27)
                {
                    builder.Append(" and a.shopid=" + this.admin_info.id);
                }
            }
            return builder.ToString();
        }

        protected void ddlGroupId_SelectedIndexChanged(object sender, EventArgs e)
        {
            base.Response.Redirect(CombUrlTxt("user_list.aspx", "group_id={0}&keywords={1}", new string[] { this.ddlGroupId.SelectedValue, this.keywords }));
        }

        protected string GetNickName(string openid)
        {
            if (string.IsNullOrEmpty(openid))
            {
                return "";
            }
            MxWeiXinPF.BLL.users users = new MxWeiXinPF.BLL.users();
            return users.GetNickName(openid);
        }

        private int GetPageSize(int _default_size)
        {
            int num;
            if (int.TryParse(Utils.GetCookie("user_list_page_size"), out num) && (num > 0))
            {
                return num;
            }
            return _default_size;
        }

        protected string GetShopName(string shopid)
        {
            MxWeiXinPF.BLL.manager manager = new MxWeiXinPF.BLL.manager();
            return manager.GetShopName(shopid);
        }

        protected string GetUserStatus(int status)
        {
            string str = string.Empty;
            switch (status)
            {
                case 0:
                    return "正常";

                case 1:
                    return "待验证";

                case 2:
                    return "待审核";

                case 3:
                    return "已禁用";
            }
            return str;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                base.ChkAdminLevel("user_list", MXEnums.ActionEnum.View.ToString());
                MxWeiXinPF.Model.manager weiXinCode = base.GetAdminInfo();
                this.wid = weiXinCode.id;
                this.group_id = MXRequest.GetQueryInt("a.group_id");
                this.keywords = MXRequest.GetQueryString("a.keywords");
                this.pageSize = this.GetPageSize(10);
                DataSet ds = bcoupon.GetListByPage(" status = 1 ", " id asc", 1, 1);
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                     mcoupon =  bcoupon.DataTableToList(ds.Tables[0])[0];
                }
                if (!this.Page.IsPostBack)
                {
                    this.admin_info = base.GetAdminInfo();
                    this.TreeBind("is_lock=0");
                    BindCoupons();
                    this.RptBind(" a.id>0" + this.CombSqlTxt(this.wid, this.group_id, this.keywords), "reg_time desc,id desc");
                }
            }
            catch
            {


            }

        }

        private void RptBind(string _strWhere, string _orderby)
        {
            try
            {
                this.page = MXRequest.GetQueryInt("a.page", 1);
                if (this.group_id > 0)
                {
                    this.ddlGroupId.SelectedValue = this.group_id.ToString();
                }
                this.txtKeywords.Text = this.keywords;
                this.rptList.DataSource = new MxWeiXinPF.BLL.users().GetListEx(this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
                this.rptList.DataBind();
                this.txtPageNum.Text = this.pageSize.ToString();
                string linkUrl =CombUrlTxt("user_list.aspx", "group_id={0}&keywords={1}&page={2}", new string[] { this.group_id.ToString(), this.keywords, "__id__" });
                this.PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, linkUrl, 8);
            }
            catch
            {


            }

        }
        public string CombUrlTxt(string _url, string _keys, params string[] _values)
        {
            StringBuilder urlParams = new StringBuilder();
            try
            {
                string[] keyArr = _keys.Split(new char[] { '&' });
                for (int i = 0; i < keyArr.Length; i++)
                {
                    if (!string.IsNullOrEmpty(_values[i]) && _values[i] != "0")
                    {
                        _values[i] = Utils.UrlEncode(_values[i]);
                        urlParams.Append(string.Format("a." + keyArr[i], _values) + "&");
                    }
                }
                if (!string.IsNullOrEmpty(urlParams.ToString()) && _url.IndexOf("?") == -1)
                    urlParams.Insert(0, "?");
                //李朴-----add  2014-3-30 begin ----
                if (!string.IsNullOrEmpty(urlParams.ToString()) && _url.Contains("&") && _url.LastIndexOf("&") < (_url.Length - 1))
                {
                    _url += "&";
                }
                //李朴-----add  2014-3-30 end ----
            }
            catch
            {
                return _url;
            }
            return _url + Utils.DelLastChar(urlParams.ToString(), "&");
        }
        public string CombUrlTxt2(string _url, string _keys, params string[] _values)
        {
            StringBuilder urlParams = new StringBuilder();
            try
            {
                string[] keyArr = _keys.Split(new char[] { '&' });
                for (int i = 0; i < keyArr.Length; i++)
                {
                    if (!string.IsNullOrEmpty(_values[i]) && _values[i] != "0")
                    {
                        _values[i] = Utils.UrlEncode(_values[i]);
                        urlParams.Append(string.Format(keyArr[i], _values) + "&");
                    }
                }
                if (!string.IsNullOrEmpty(urlParams.ToString()) && _url.IndexOf("?") == -1)
                    urlParams.Insert(0, "?");
                //李朴-----add  2014-3-30 begin ----
                if (!string.IsNullOrEmpty(urlParams.ToString()) && _url.Contains("&") && _url.LastIndexOf("&") < (_url.Length - 1))
                {
                    _url += "&";
                }
                //李朴-----add  2014-3-30 end ----
            }
            catch
            {
                return _url;
            }
            return _url + Utils.DelLastChar(urlParams.ToString(), "&");
        }
        private void TreeBind(string strWhere)
        {
            try
            {
                MxWeiXinPF.BLL.user_groups _groups = new MxWeiXinPF.BLL.user_groups();
                DataTable table = _groups.GetList(0, strWhere, "id desc").Tables[0];
                this.ddlGroupId.Items.Clear();
                this.ddlGroupId.Items.Add(new ListItem("所有会员组", ""));
                foreach (DataRow row in table.Rows)
                {
                    this.ddlGroupId.Items.Add(new ListItem(row["title"].ToString(), row["id"].ToString()));
                }
            }
            catch
            {


            }

        }

        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int num;
            if (int.TryParse(this.txtPageNum.Text.Trim(), out num) && (num > 0))
            {
                Utils.WriteCookie("user_list_page_size", num.ToString(), 0x3840);
            }
            base.Response.Redirect(CombUrlTxt("user_list.aspx", "group_id={0}&keywords={1}", new string[] { this.group_id.ToString(), this.keywords }));
        }

        protected void rptList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string id = e.CommandArgument.ToString();

            MxWeiXinPF.BLL.users buser = new MxWeiXinPF.BLL.users();
            BLL.wx_shop_coupon_data bcoupon = new BLL.wx_shop_coupon_data();
            if (e.CommandName == "send_ticket")
            {
                Model.users muser = buser.GetModel(Convert.ToInt32(id));
                if (muser != null && mcoupon != null)
                {
                    DataSet ds = bcoupon.GetList(string.Format("senduid = {0} and couponid={1} ", id, mcoupon.id));
                    if (ds == null || ds.Tables[0].Rows.Count == 0)
                    {
                        List<Model.wx_shop_coupon_data> datas = bcoupon.DataTableToList(ds.Tables[0]);
                        if (datas.Count >= mcoupon.numperuser)
                        {
                            base.JscriptMsg("送券失败,用户领券数量大于设定值！", CombUrlTxt("user_list.aspx", "group_id={0}&keywords={1}", new string[] { this.group_id.ToString(), this.keywords }), "Success");
                            return;
                        }
                        else
                        {
                            Model.wx_shop_coupon_data thecoupon = new Model.wx_shop_coupon_data();
                            thecoupon.couponid = mcoupon.id;
                            thecoupon.shopid = base.GetAdminInfo().id;
                            thecoupon.openid = muser.wxOpenId;
                            thecoupon.gettype = 0;
                            thecoupon.status = 0;
                            thecoupon.gettime = DateTime.Now;
                            thecoupon.usetime = DateTime.Now;
                            thecoupon.senduid = muser.id;
                            thecoupon.ordersn = 0;
                            thecoupon.sendmsgstate = 0;
                            thecoupon.sendmsgtime = DateTime.Now;
                           
                            if (bcoupon.Add(thecoupon) > 0)
                            {
                                
                                //送券成功,增加日志记录
                                Model.wx_shop_coupon_log log = new Model.wx_shop_coupon_log();
                                log.shopid = base.GetAdminInfo().id;
                                log.openid = muser.wxOpenId;
                                log.times = DateTime.Now;
                                log.couponid = mcoupon.id;
                                log.orderid = 0;
                                log.explain = "后台赠送用户";
                                log.remark = " ";
                                log.exstr1 = " ";
                                new BLL.wx_shop_coupon_log().Add(log);
                                base.JscriptMsg("送券成功！", CombUrlTxt("user_list.aspx", "group_id={0}&keywords={1}", new string[] { this.group_id.ToString(), this.keywords }), "Success");
                                return;                           
                            }

                        }
                    }
                }
            }
            base.JscriptMsg("送券失败,用户领券数量大于设定值！", CombUrlTxt("user_list.aspx", "group_id={0}&keywords={1}", new string[] { this.group_id.ToString(), this.keywords }), "Success");
            return;
        }

        public bool GetSendTickState(int id)
        {
            BLL.users buser = new BLL.users();
            Model.users muser = buser.GetModel(id);
            if (muser != null)
            {
                if (mcoupon != null)
                {
                    DataSet mcoupondata = new BLL.wx_shop_coupon_data().GetList(string.Format("senduid = {0} and couponid={1} ", id, mcoupon.id));
                    if (mcoupondata == null || mcoupondata.Tables[0].Rows.Count == 0)
                    {
                        return true;
                    }
                }
            }
            return false;
        }


        private void BindCoupons()
        {
            BLL.wx_shop_coupon bll = new BLL.wx_shop_coupon();

            Model.manager weixin = base.GetAdminInfo();
            DataSet ds = bll.GetList(" status = 1 and timeend >'" + DateTime.Now.ToString() + "' ");
            this.ddlCouponId.Items.Clear();
            this.ddlCouponId.Items.Add(new ListItem("未选择", "0"));
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                string Id = dr["id"].ToString();
                string Title = dr["couponname"].ToString().Trim();
                this.ddlCouponId.Items.Add(new ListItem(Title, Id));
            }
        }
    }
}